<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\facade\View;

class Menu extends BaseController
{
    public function getMenuList()
    {
        $where = [];
        $where[] = ['status', '=', 1];

        if (!is_admin()) {
            $rule = Db::name('admin_role')->where('id', session('admin_auth.role_id'))->value('rule');
            $where[] = ['id', 'in', $rule];
        }

        $result = Db::name('admin_menu')
            ->field('id, title, menu_id, control, action, icon, type, openType')
            ->where($where)
            ->order('sort asc,id asc')
            ->select();

        $menu = prepareMenu($result);

        header('Content-Type:application/json; charset=utf-8');
        return json($menu);
    }


    public function index()
    {
        return View::fetch();
    }

    public function getMenu()
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }
        
        $data = DB::name('admin_menu')
            ->field('id, title, menu_id, control, action, icon, type, openType, powerType, sort, status')
            ->order('sort asc,id asc')
            ->select();

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => 0,
            'data'=> $data
        );
        return json($data);
    }

    public function add()
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        return View::fetch();
    }

    public function getMenuTree()
    {
        $where['status'] = 1;

        $result = Db::name('admin_menu')
            ->field('id, title, menu_id as parentId')
            ->where($where)
            ->order('sort asc,id asc')
            ->select();

        $menu = $this->prepareMenu($result);
        header('Content-Type:application/json; charset=utf-8');
        $data = [
            'status' => [
                'code' => 200,
                'message' => 'ok'
            ],
            'data' => $menu
        ];
        return json($data);
    }

    protected function prepareMenu($param)
    {

        $parent = []; //父类
        $child = [];  //子类

        foreach($param as $key=>$vo){
            if($vo['parentId'] == 0){
                $parent[] = $vo;

            }else{
                $child[] = $vo;
            }
        }

        foreach($parent as $key=>$vo){
            foreach($child as $k=>$v){
                if($v['parentId'] == $vo['id']){
                    $parent[$key]['children'][] = $v;
                }
            }
        }

        return $parent;
    }


    public function save(Request $request)
    {
        $post = $request->post();

        $a = explode('/',$post['href']);
        if (empty($a[0])) {
            return $this->outputAjax('节点路径格式错误！');
        }
        if (empty($post['tree_select_nodeId'])) {
            $menu_id = 0;
            $type = 0;
            $openType = '';
            $powerType = 0;
        } else {
            $menu_id = $post['tree_select_nodeId'];
            $type = 1;
            $openType = '_iframe';
            $res = Db::name('admin_menu')->where(array('id' => $menu_id))->value('menu_id');
            if ($res != 0) {
                $powerType = 2;
            } else {
                $powerType = 1;
            }
        }
        if ($post['status'] == 'on') {
            $status = 1;
        } else {
            $status = 0;
        }

        $insert = array(
            'menu_id' => $menu_id,
            'title' => $post['title'],
            'icon' => $post['icon'],
            'sort' => $post['sort'],
            'control' => $a[0],
            'action' => $a[1],
            'status' => $status,
            'type' => $type,
            'openType' => $openType,
            'powerType' => $powerType,
            'add_time' => time(),
            'update_time' => time()
        );

        if (!DB::name('admin_menu')->insert($insert)) {
            return $this->outputAjax('提交失败！');
        }
        return $this->outputAjax('提交成功！',0);
    }

    public function edit(Request $request)
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $id = $request->get('id');

        $inf = Db::name('admin_menu')
            ->where(array('id' => $id))
            ->field('id, menu_id, title, control, action, status, sort, icon')
            ->find();
        $inf['href'] = $inf['control'].'/'.$inf['action'];
        View::assign('inf', $inf);
        return View::fetch();
    }


    public function modify(Request $request)
    {
        $post = $request->post();

        $a = explode('/',$post['href']);
        if (empty($a[0])) {
            return $this->outputAjax('节点路径格式错误！');
        }
        if (empty($post['tree_select_nodeId'])) {
            $menu_id = 0;
            $type = 0;
            $openType = '';
            $powerType = 0;
        } else {
            $menu_id = $post['tree_select_nodeId'];
            $type = 1;
            $openType = '_iframe';
            $res = DB::name('admin_menu')->where(array('id' => $menu_id))->value('menu_id');
            if ($res != 0) {
                $powerType = 2;
            } else {
                $powerType = 1;
            }

        }
        if ($post['status'] == 'on') {
            $status = 1;
        } else {
            $status = 0;
        }

        $update = array(
            'id' => $post['id'],
            'menu_id' => $menu_id,
            'title' => $post['title'],
            'icon' => $post['icon'],
            'sort' => $post['sort'],
            'control' => $a[0],
            'action' => $a[1],
            'status' => $status,
            'type' => $type,
            'openType' => $openType,
            'powerType' => $powerType,
            'update_time' => time()
        );

        if (!Db::name('admin_menu')->update($update)) {
            return $this->outputAjax('提交失败！');
        }
        return $this->outputAjax('提交成功！',0);
    }


    /*
     * 节点删除
     */
    public function delete(Request $request)
    {
        $id = $request->post('id');
        if(!$id){
            return $this->outputAjax('参数不足！');
        }

        $arr = Db::name('admin_menu')->field('id, menu_id')->select();
        $all = $this->scanNodeOfTree($arr,$id);
        $result = Db::name('admin_menu')->where(['id'=>['in',$all]])->delete();

        if(!$result){
            return $this->outputAjax('删除失败！');
        }
        return $this->outputAjax('删除成功！',0);

    }

    //获取自己和子集id
    public function scanNodeOfTree($result,$fid){
        $checkexist = false;
        $arr = $fid.',';
        for ($i=0; $i<count($result); $i++){
            if($fid == $result[$i]['menu_id']){
                $checkexist = true;
                $arr .= $this->scanNodeOfTree($result,$result[$i]['id']).',';
            }
        }
        if(!$checkexist){
            return $fid;
        }
        return $arr;
    }


    public function toggle(Request $request)
    {
        $id = $request->post('id');
        if (!$id) {
            return $this->outputAjax();
        }
        $inf = Db::name('admin_menu')->find($id);

        if (empty($inf)) {
            return $this->outputAjax('参数错误！');
        }

        if (!in_array($inf['status'], array(1, 0))) {
            return $this->outputAjax('参数错误[1]！');
        }

        $status = $inf['status'] == 1 ? 0 : 1;

        $update = array(
            'id' => $id,
            'status' => $status,
        );
        if(!Db::name('admin_menu')->update($update)) {
            return $this->outputAjax('操作失败！');
        }

        return $this->outputAjax('操作成功！',0);
    }

    public function sort(Request $request)
    {
        $post = $request->post();

        if (empty($post)) {
            return $this->outputAjax('参数缺失！');
        }

        if (!is_numeric($post['sort'])) {
            return $this->outputAjax('请填写数字！');
        }

        if ($post['sort'] < 0 || $post['sort'] > 999) {
            return $this->outputAjax('排序数字在0-999之间！');
        }

        $res = Db::name('admin_menu')->where(array('id'=>$post['id']))->find();
        if (!$res) {
            return $this->outputAjax('参数错误！');
        }

        if (!Db::name('admin_menu')->where(['id'=>$post['id']])->update(['sort' => $post['sort']])) {
            return $this->outputAjax('排序失败！');
        }

        return $this->outputAjax('排序成功！', 0);
    }

}